package com.wmh.baseservice.user.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wmh.baseservice.admin.pojo.AdProfit;
import com.wmh.baseservice.admin.service.AdProfitService;
import com.wmh.baseservice.common.ex.ServiceException;
import com.wmh.baseservice.common.mybatisplus.methods.CommonServiceImpl;
import com.wmh.baseservice.common.utils.CommUtil;
import com.wmh.baseservice.common.utils.QrCodeUtil;
import com.wmh.baseservice.common.wechat.mp.template.WxSubMsgUtils;
import com.wmh.baseservice.merchant.pojo.*;
import com.wmh.baseservice.merchant.service.MerchantIncomeExpendService;
import com.wmh.baseservice.merchant.service.MerchantInfoService;
import com.wmh.baseservice.merchant.service.MerchantPlotRegionService;
import com.wmh.baseservice.merchant.service.MerchantVegetableService;
import com.wmh.baseservice.system.pojo.SysMessage;
import com.wmh.baseservice.system.pojo.SysParams;
import com.wmh.baseservice.system.service.SysMessageService;
import com.wmh.baseservice.system.service.SysParamsService;
import com.wmh.baseservice.user.mapper.UsVegetableOrderMapper;
import com.wmh.baseservice.user.pojo.UsIncomeExpend;
import com.wmh.baseservice.user.pojo.UsInfo;
import com.wmh.baseservice.user.pojo.UsParentOrder;
import com.wmh.baseservice.user.pojo.UsVegetableOrder;
import com.wmh.baseservice.user.service.UsIncomeExpendService;
import com.wmh.baseservice.user.service.UsInfoService;
import com.wmh.baseservice.user.service.UsParentOrderService;
import com.wmh.baseservice.user.service.UsVegetableOrderService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @author mmx generator
 * @since 2021-12-24
 */
@Service
public class UsVegetableOrderServiceImpl extends CommonServiceImpl<UsVegetableOrderMapper, UsVegetableOrder> implements UsVegetableOrderService {

    @Resource
    private SysParamsService sysParamsService;
    @Resource
    private MerchantInfoService merchantInfoService;
    @Resource
    private MerchantPlotRegionService merchantPlotRegionService;
    @Resource
    private MerchantVegetableService merchantVegetableService;
    @Resource
    private MerchantIncomeExpendService merchantIncomeExpendService;
    @Resource
    private UsInfoService usInfoService;
    @Resource
    private UsVegetableOrderService usVegetableOrderService;
    @Resource
    private AdProfitService adProfitService;
    @Resource
    private UsVegetableOrderMapper usVegetableOrderMapper;
    @Resource
    private UsIncomeExpendService usIncomeExpendService;
    @Resource
    private SysMessageService sysMessageService;
    @Resource
    private UsParentOrderService usParentOrderService;

    /**
     * 果蔬产品余额支付
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void balancePay(UsVegetableOrder usVegetableOrder, UsInfo usInfo) {
        //修改订单状态
        usVegetableOrder.setStatus(1);
        usVegetableOrder.setPayTime(new Date());
        if (CommUtil.checkNull(usVegetableOrder.getAddressId())) {
            usVegetableOrder.setCourierStatus(0);
        }
        //3、用户余额扣减
        usInfo.setBalance(usInfo.getBalance().subtract(usVegetableOrder.getRealPrice()));
        if (!usInfoService.updateById(usInfo)) {
            throw new ServiceException();
        }
        //添加流水支出
        UsIncomeExpend usIncomeExpend = new UsIncomeExpend().setOrderNum(usVegetableOrder.getOrderNum()).setType(1).setStatus(-1).setUsId(usVegetableOrder.getUsId()).setRemark("余额摘种支出").setMoney(usVegetableOrder.getRealPrice());
        if (!usIncomeExpendService.save(usIncomeExpend)) {
            throw new ServiceException();
        }
        if (!usVegetableOrderService.updateById(usVegetableOrder)) {
            throw new ServiceException();
        }
        //判断是否有上级推广佣金
        MerchantVegetable merchantVegetable = merchantVegetableService.getByIdForUpdate(JSONObject.parseObject(
                JSONArray.parseArray(usVegetableOrder.getSnapshot()).get(0).toString()
        ).getLong("id"));
        if (CommUtil.checkNull(merchantVegetable.getCommission())) {
            if (CommUtil.checkNull(usInfo) && usInfo.getInviteId() != -1) {
                UsInfo parentInfo = usInfoService.getByIdForUpdate(usInfo.getInviteId());
                //添加用户冻结流水
                UsIncomeExpend freezeIncome = new UsIncomeExpend().setUsId(parentInfo.getId()).setStatus(1).setType(1).setRemark("摘种商品佣金").setOrderNum(usVegetableOrder.getOrderNum())
                        .setMoney(merchantVegetable.getCommission()).setHasFreeze(-1);
                if (!usIncomeExpendService.save(freezeIncome)) {
                    throw new ServiceException();
                }
            }
        }

        //查出当前果蔬所属商家
        MerchantPlotRegion region = merchantPlotRegionService.getById(merchantVegetable.getRegionId());

        //给商家发送消息
        SysMessage sysMessage = new SysMessage().setMerchantId(usVegetableOrder.getMerchantId()).setTitle("您有一个新的摘种订单，请到商家后台及时处理")
                .setContent("订单号:" + usVegetableOrder.getOrderNum() + "购买人微信昵称：" + usInfo.getNick());
        UsInfo merchantUs = usInfoService.getOne(new QueryWrapper<UsInfo>().eq(UsInfo.MERCHANT_ID, region.getMerchantId()));
        sysMessage.setUsId(merchantUs.getId());
        if (!sysMessageService.save(sysMessage)) {
            throw new ServiceException();
        }

        //发送模板消息:新订单通知
        WxSubMsgUtils.newOrder(merchantUs.getMpOpenId(), "您有一个新的果蔬订单", usVegetableOrder.getPayTime(), "果蔬产品",
                usInfo.getNick(), usVegetableOrder.getOrderNum(), "请及时进入小程序果蔬订单列表发货处理哦~");

    }

    @Override
    public void cancelOrder(Long value) {
        usVegetableOrderMapper.cancelOrder(value);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void weChatPay(String orderNum) {
        UsVegetableOrder usVegetableOrder = getOneForUpdate(new QueryWrapper<UsVegetableOrder>().eq(UsVegetableOrder.ORDER_NUM, orderNum));
        usVegetableOrder.setStatus(1);
        usVegetableOrder.setPayTime(new Date());
        usVegetableOrder.setPayType(2);
        if (CommUtil.checkNull(usVegetableOrder.getAddressId())) {
            usVegetableOrder.setCourierStatus(0);
        }
        //添加流水支出
        UsIncomeExpend usIncomeExpend = new UsIncomeExpend().setOrderNum(usVegetableOrder.getOrderNum()).setType(1).setStatus(-1).setUsId(usVegetableOrder.getUsId()).setRemark("微信支付摘种支出").setMoney(usVegetableOrder.getRealPrice());
        if (!usIncomeExpendService.save(usIncomeExpend)) {
            throw new ServiceException();
        }


        //判断是否有上级推广佣金
        MerchantVegetable merchantVegetable = merchantVegetableService.getByIdForUpdate(JSONObject.parseObject(
                JSONArray.parseArray(usVegetableOrder.getSnapshot()).get(0).toString()
        ).getLong("id"));
        if (CommUtil.checkNull(merchantVegetable.getCommission())) {
            UsInfo usInfo = usInfoService.getByIdForUpdate(usVegetableOrder.getUsId());
            if (CommUtil.checkNull(usInfo) && usInfo.getInviteId() != -1) {
                UsInfo parentInfo = usInfoService.getByIdForUpdate(usInfo.getInviteId());
                //添加用户冻结流水
                UsIncomeExpend freezeIncome = new UsIncomeExpend().setUsId(parentInfo.getId()).setStatus(1).setType(1).setRemark("摘种商品佣金").setOrderNum(usVegetableOrder.getOrderNum())
                        .setMoney(merchantVegetable.getCommission()).setHasFreeze(-1);
                if (!usIncomeExpendService.save(freezeIncome)) {
                    throw new ServiceException();
                }
            }
        }

        //查出当前果蔬所属商家
        MerchantPlotRegion region = merchantPlotRegionService.getById(merchantVegetable.getRegionId());
        //给商家发送消息
        UsInfo usInfo = usInfoService.getByIdForUpdate(usVegetableOrder.getUsId());
        SysMessage sysMessage = new SysMessage().setMerchantId(usVegetableOrder.getMerchantId()).setTitle("您有一个新的摘种订单，请到商家后台及时处理")
                .setContent("订单号:" + usVegetableOrder.getOrderNum() + "购买人微信昵称：" + usInfo.getNick());
        UsInfo merchantUs = usInfoService.getOneForUpdate(new QueryWrapper<UsInfo>().eq(UsInfo.MERCHANT_ID, region.getMerchantId()));
        sysMessage.setUsId(merchantUs.getId());
        if (!sysMessageService.save(sysMessage)) {
            throw new ServiceException();
        }

        //查询是否有父订单
        UsParentOrder parentOrder = usParentOrderService.getOne(new QueryWrapper<UsParentOrder>().like(UsParentOrder.SON_ORDER, usVegetableOrder.getOrderNum()));
        if (CommUtil.checkNull(parentOrder)) {
            //更新所有子订单状态信息
            JSONArray array = JSONArray.parseArray(parentOrder.getSonOrder());
            array.forEach(order -> {
                UsVegetableOrder sonOrder = getOne(new QueryWrapper<UsVegetableOrder>()
                        .eq(UsVegetableOrder.ORDER_NUM, order.toString()));
                sonOrder.setStatus(usVegetableOrder.getStatus()).setPayTime(usVegetableOrder.getPayTime())
                        .setPayType(usVegetableOrder.getPayType());
                if (CommUtil.checkNull(usVegetableOrder.getAddressId())){
                    sonOrder.setCourierStatus(usVegetableOrder.getCourierStatus());
                }
                if (!updateById(usVegetableOrder)) {
                    throw new ServiceException("发货批量更新订单状态错误");
                }
            });
        } else {
            if (!updateById(usVegetableOrder)) {
                throw new ServiceException();
            }
        }
        //删除购物车

        //发送模板消息:新订单通知
        WxSubMsgUtils.newOrder(merchantUs.getMpOpenId(), "您有一个新的果蔬订单", usVegetableOrder.getPayTime(), "果蔬产品",
                usInfo.getNick(), usVegetableOrder.getOrderNum(), "请及时进入小程序果蔬订单列表发货处理哦~");
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void confirm(UsVegetableOrder usVegetableOrder) {
        //1、平台抽成
        SysParams serviceCost = sysParamsService.getOneForUpdate(new QueryWrapper<SysParams>().eq(SysParams.PARAM_NAME, "serviceCost"));
        if (!CommUtil.checkNull(serviceCost)) {
            throw new ServiceException("缺少系统参数");
        }
        BigDecimal adCost = usVegetableOrder.getRealPrice().multiply(new BigDecimal(serviceCost.getValue()));
        //最小抽1分钱
        if (adCost.compareTo(new BigDecimal("0.01")) <= 0) {
            adCost = new BigDecimal("0.01");
        }
        final BigDecimal[] merchantProfit = {usVegetableOrder.getRealPrice().subtract(adCost)};
        //添加平台收益流水
        AdProfit adProfit = new AdProfit().setMoney(adCost).setOrigin(String.format("果蔬%s抽成", usVegetableOrder.getType() == 1 ? "采摘" : "种植"));
        if (!adProfitService.save(adProfit)) {
            throw new ServiceException(adProfit.toString());
        }

        MerchantInfo merchantInfo = merchantInfoService.getByIdForUpdate(usVegetableOrder.getMerchantId());
        //判断当前果蔬订单所属收益是出租还是原持有商家,如果是属于原持有商家，那么给他的合伙人分配收益（如果有的话），如果是租赁的商家，那么直接给该租赁商家分配100%收益
        if (usVegetableOrder.getMerchantType() == 0) {
            //查出所有合伙人
            List<MerchantInfo> merchantInfos = merchantInfoService.listForUpdate(new QueryWrapper<MerchantInfo>().eq(MerchantInfo.PARENT_ID, merchantInfo.getUsId()));
            merchantInfos.forEach(info -> {
                //合伙人收益计算
                BigDecimal profit = merchantProfit[0].multiply(BigDecimal.valueOf(info.getShares()));
                merchantProfit[0] = merchantProfit[0].subtract(profit);
                //合伙人余额增加
                info.setBalance(info.getBalance().add(profit));
                if (!merchantInfoService.updateById(info)) {
                    throw new ServiceException(info.toString());
                }
                //添加收入流水
                MerchantIncomeExpend merchantIncomeExpend = new MerchantIncomeExpend().setMoney(profit).setOrderNum(usVegetableOrder.getOrderNum())
                        .setRemark(String.format("果蔬%s收益", usVegetableOrder.getType() == 1 ? "采摘" : "种植")).setStatus(1).setMerchantId(info.getId());
                if (!merchantIncomeExpendService.save(merchantIncomeExpend)) {
                    throw new ServiceException(merchantIncomeExpend.toString());
                }
            });
        }

        //主商家余额添加
        merchantInfo.setBalance(merchantInfo.getBalance().add(merchantProfit[0]));
        if (!merchantInfoService.updateById(merchantInfo)) {
            throw new ServiceException(merchantInfo.toString());
        }
        //添加主商家收入流水
        MerchantIncomeExpend merchantIncomeExpend = new MerchantIncomeExpend().setMoney(merchantProfit[0]).setOrderNum(usVegetableOrder.getOrderNum())
                .setRemark(String.format("果蔬%s收益", usVegetableOrder.getType() == 1 ? "采摘" : "种植")).setStatus(1).setMerchantId(merchantInfo.getId());
        if (!merchantIncomeExpendService.save(merchantIncomeExpend)) {
            throw new ServiceException(merchantIncomeExpend.toString());
        }

        //查询是否有父订单
        UsParentOrder parentOrder = usParentOrderService.getOne(new QueryWrapper<UsParentOrder>().like(UsParentOrder.SON_ORDER, usVegetableOrder.getOrderNum()));
        if (CommUtil.checkNull(parentOrder)) {
            //更新所有子订单状态信息
            JSONArray array = JSONArray.parseArray(parentOrder.getSonOrder());
            array.forEach(order -> {
                UsVegetableOrder sonOrder = getOne(new QueryWrapper<UsVegetableOrder>()
                        .eq(UsVegetableOrder.ORDER_NUM, order.toString()));
                sonOrder.setStatus(usVegetableOrder.getStatus());
                if (CommUtil.checkNull(usVegetableOrder.getAddressId())){
                    sonOrder.setCourierStatus(usVegetableOrder.getCourierStatus());
                }else{
                    sonOrder.setTakeTime(usVegetableOrder.getTakeTime());
                }
                if (!updateById(usVegetableOrder)) {
                    throw new ServiceException("发货批量更新订单状态错误");
                }
            });
        } else {
            if (!updateById(usVegetableOrder)) {
                throw new ServiceException();
            }
        }
    }

    @Override
    public List<UsVegetableOrder> autoDeliver(String value) {
        return usVegetableOrderMapper.autoDeliver(value);
    }

    @Override
    public int queryShortOrder(Long usId) {
        return usVegetableOrderMapper.queryShortOrder(usId);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void shopCarWeChatPay(String orderNum) {
        UsParentOrder usParentOrder = usParentOrderService.getOneForUpdate(new QueryWrapper<UsParentOrder>().eq(UsParentOrder.ORDER_NUM, orderNum));
        usParentOrder.setStatus(1).setPayTime(new Date());
        JSONArray array = JSONArray.parseArray(usParentOrder.getSonOrder());
        array.forEach(item -> {
            weChatPay(item.toString());
        });
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deliver(UsVegetableOrder vegetableOrder, UsParentOrder parentOrder) {
        //是否有父订单
        if (CommUtil.checkNull(parentOrder)) {
            //更新所有子订单状态信息
            JSONArray array = JSONArray.parseArray(parentOrder.getSonOrder());
            array.forEach(order -> {
                UsVegetableOrder usVegetableOrder = getOne(new QueryWrapper<UsVegetableOrder>()
                        .eq(UsVegetableOrder.ORDER_NUM, order.toString()));
                usVegetableOrder.setCourierStatus(vegetableOrder.getCourierStatus())
                        .setCourierNumber(vegetableOrder.getCourierNumber())
                        .setCourierCompany(vegetableOrder.getCourierCompany());
                if (!updateById(usVegetableOrder)) {
                    throw new ServiceException("发货批量更新订单状态错误");
                }
            });
        } else {
            //单独更新该订单状态
            if (!updateById(vegetableOrder)) {
                throw new ServiceException("发货单独更新订单状态错误");
            }
        }
    }
}
